package com.adityayadav.peekaboo;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import com.adityayadav.parallelism.core.RecurringTask;
import com.adityayadav.parallelism.core.ThreadPool;

public class RecurringWorkerTask extends RecurringTask{

	private InputStream in = null;
	private OutputStream out = null;

	private byte[] buffer = new byte[0];
	private byte[] buf = new byte[100000];// this is the temp read buffer
	private Socket clientSocket;
	private boolean closed = false;
	
	public static final int INITIAL=0;
	public static final int OUTGOING_CONNECTED=1;
	private int state = INITIAL;
	
	public RecurringWorkerTask(ThreadPool taskThreadPool, Socket clientSocket,InputStream in, OutputStream out) {
		super(taskThreadPool);
		this.clientSocket = clientSocket;
		this.in = in;
		this.out = out;
		
	}
	@Override
	public void commit() throws Exception {
		if (!closed) taskThreadPool.addTask(this);
	}

	@Override
	public void rollback() throws Exception {
		if (!closed) taskThreadPool.addTask(this);
	}
	@Override
	public void process() throws Exception {
		try {
			int numRead = in.read(buf);
			if (numRead ==-1) throw new Exception();
			byte[] part = new byte[numRead];
			System.arraycopy(buf,0,part,0,numRead);
			//send to the other end
			out.write(part);
			// add to the buffer
			addToBuffer(part);
		} catch (Exception e){
			closeEverything();
		}
	}

	public byte[] getBuffer() {
		return buffer;
	}

	public void setBuffer(byte[] buffer) {
		this.buffer = buffer;
	}

	public void addToBuffer(byte[] part){
		int length = buffer.length + part.length;
		byte[] buffer2 = new byte[length];
		System.arraycopy(buffer, 0, buffer2, 0, buffer.length);
		System.arraycopy(part, 0, buffer2, buffer.length, part.length);
		buffer = buffer2;
	}
	
	public void closeEverything(){
		closed=true;
	
		try {
			in.close();
		} catch (Exception e){}
		try {
			out.close();
		} catch (Exception e){}
		//SocketRegistry.getInstance().close(clientSocket); this will delete the socket entry from the registry. We don't want that as we are peeking in to payloads
	}
}
